﻿using SuperiorShopBussinessService;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using SuperiorCommon;
using SuperiorModel;
using Redis;
using WxPayAPIMobileShopCode.Common.Helpers;

namespace H5.SuperiorShop.Controllers
{
    [CheckLoginFitler]
    [JsonException]
    public class OrderController : BaseController
    {
        private readonly IProductService _IProductService;
        private readonly ISetService _ISetService;
        private readonly IOrderService _IOrderService;

        public OrderController(IProductService IProductService, ISetService ISetService, IOrderService IOrderService)
        {
            _IProductService = IProductService;
            _ISetService = ISetService;
            _IOrderService = IOrderService;

        }
        protected override void Dispose(bool disposing)
        {
            this._IProductService.Dispose();
            this._ISetService.Dispose();
            base.Dispose(disposing);
        }
        // GET: Order
        public ActionResult Index()
        {
            return View();
        }
        [CheckUrlFitler]
        public ActionResult SureOrder(string goodList)
        {
            var model = SuperiorCommon.Json.ToObject<List<Api_SureOrderModel>>(goodList);
            //记录当前URL
            CookieHelper.SetCookie("SUREURL", Request.RawUrl, DateTime.Now.AddMinutes(20));
            return View(model);
        }
        /// <summary>
        /// 计算运费
        /// </summary>
        /// <param name="criteria"></param>
        /// <returns></returns>
        [AjaxOnly]
        [HttpPost]
        public JsonResult CountShipAmount(Api_CountShipAmountCriteria criteria)
        {
            var spid = base.ValidataParms(criteria.Spid);
            if (spid == null)
                return Error("非法参数");
            criteria.UserId = UserContext.User.Id;
            var url = ConfigSettings.Instance.ApiHost + "Api/Order/CountShipAmount";
            LogManger.Instance.WriteLog("url:"+url);
            var response= SuperiorCommon.Request.HttpRequest.PostDataToUrl(criteria.ToJson(),url);
            LogManger.Instance.WriteLog("response:" + response);
            var retModel = SuperiorCommon.Json.ToObject<ApiResponseModel<decimal>>(response);
            if (retModel.Code == 0)
                return Error(retModel.Message);
            return Success(retModel.Data);
        }

        [HttpPost]
        [AjaxOnly]
        public JsonResult Create(Api_CreateOrderCriteria criteria)
        {
            criteria.UserId = UserContext.User.Id;
            var url = ConfigSettings.Instance.ApiHost + "Api/Order/CreateOrder_Cart";
            var response = SuperiorCommon.Request.HttpRequest.PostDataToUrl(criteria.ToJson(), url);
            var retModel = SuperiorCommon.Json.ToObject<ApiResponseModel<Api_CreateOrderResultModel>>(response);
            if (retModel.Code == 0)
                return Error(retModel.Message);
            return Success(retModel.Data);
        }
        /// <summary>
        /// 我的订单列表
        /// </summary>
        /// <returns></returns>
        /// 
        [CheckUrlFitler]
        public ActionResult MyOrders(int orderStatus =999)
        {
            var criteria = new Api_OrderListCriteria()
            {
                Spid = base.CheckSpid().ToString(),
                UserId = UserContext.DeUserId,
                OffSet = 0,
                Size = 10,
                OrderStatus = orderStatus
            };
            var res = _IOrderService.Api_GetOrderList(criteria);
            return View(res);
        }
        /// <summary>
        /// 用户下拉刷新获取订单数据
        /// </summary>
        /// <param name="criteria"></param>
        /// <returns></returns>
        [AjaxOnly]
        [HttpPost]
        public JsonResult SearchOrders(Api_OrderListCriteria criteria)
        {
            criteria.Spid = base.CheckSpid().ToString();
            criteria.UserId = UserContext.DeUserId;
            var res = _IOrderService.Api_GetOrderList(criteria);
            return Success(res);
        }
        /// <summary>
        /// 申请售后服务
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        [AjaxOnly]
        public JsonResult ServiceOrder(int orderid)
        {
            var _userid = UserContext.DeUserId;
            var res = _IOrderService.Api_ServiceOrder(orderid, _userid.ToInt());
            if (!res)
                return Error("申请失败");
            return Success(true);
        }
        /// <summary>
        /// 订单详情
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        [CheckUrlFitler]
        public ActionResult Detail(int orderId)
        {
            //由于订单除了状态，都是静态数据。所有把静态数据，存进redis
            Func<Api_OrderDetail_InfoModel> fucc = delegate ()
            {
                return _IOrderService.Api_GetDetail(orderId);
            };
            var orderModel = DataIntegration.GetData<Api_OrderDetail_InfoModel>("GetDetail_" + orderId, fucc, 1);
            if (orderModel == null)
                return Error("获取出错");
            if (string.IsNullOrEmpty(orderModel.OrderNo))
            {
                RedisManager.Remove("GetDetail_" + orderId);
                return Error("获取异常");
            }
            //读取订单状态
            int orderstatus = _IOrderService.Api_GetOrderStatus(orderId);
            orderModel.OrderStatus = orderstatus;
            return View(orderModel);
        }
        /// <summary>
        /// 获取微信支付结果
        /// </summary>
        /// <param name="orderno"></param>
        /// <returns></returns>
        /// 
        [AjaxOnly]
        public JsonResult GetPayResult(string orderno)
        {
            string url = "https://api.mch.weixin.qq.com/pay/orderquery";
            WxPayData data = new WxPayData();
            data.SetValue("appid", ConfigSettings.Instance.APPID);//公众账号ID
            data.SetValue("mch_id", ConfigSettings.Instance.Merchant_Id);//商户号
            data.SetValue("out_trade_no", orderno);//微信订单号不存在，才根据商户订单号去查单
            data.SetValue("nonce_str", ToolManager.CreateShortToken());//随机字符串
            data.SetValue("sign", data.MakeSign(ConfigSettings.Instance.PaySecret));
            string xml = data.ToXml();
            string response = WeiXinHelper.Post(xml, url, false, 10);
            WxPayData result = new WxPayData();
            result.FromXml(response);
            //签名验证
            //2015-06-29 错误时没有签名
            if (result.IsSet("return_code") && result.GetValue("return_code").ToString() == "SUCCESS" && result.IsSet("sign") && result.GetValue("sign").ToString() != "")
            {
                //获取接收到的签名
                string return_sign = result.GetValue("sign").ToString();
                //在本地计算新的签名
                string cal_sign = result.MakeSign(ConfigSettings.Instance.PaySecret);
                if (cal_sign == return_sign)
                {
                    WxPayData msg = new WxPayData();
             
                    var res = new { code=result.GetValue("result_code"),msg= (result.IsSet("err_code_des") ? result.GetValue("err_code_des") : ""), state =(result.IsSet("trade_state") ? result.GetValue("trade_state") : "") };
                    return Success(res);
                }
                else
                {
                    
                    LogManger.Instance.WriteLog("查询微信订单号：" + orderno + ";接收到签名：" + return_sign + ";本地签名：" + cal_sign);
                    return Error("微信订单查询验证签名失败");
                }
            }
            else
            {
                if (result.IsSet("return_msg") && result.GetValue("return_msg").ToString() != "")
                {
                    LogManger.Instance.WriteLog("微信订单号：" + orderno + ";微信查询订单失败：" + result.GetValue("return_msg").ToString());
                    return Error(result.GetValue("return_msg").ToString());
                }
                else
                {
                    return Error("微信订单查询失败");
                }
            }
        }
        /// <summary>
        /// 获取拉起微信支付的参数
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="orderno"></param>
        /// <returns></returns>
        [AjaxOnly]
        public JsonResult GetPayData(string orderno)
        {
            string _userid = UserContext.DeUserId;
            //从redis获取拉起支付所需的缓存数据
            var res = RedisManager.Get<Api_CreateOrderResultModel>(orderno + _userid);
            if (res == null)
                return Error("获取支付数据失败");
            return Success(res);
        }
    }
}